package com.example.newhabitclock.TimeDown

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import android.os.CountDownTimer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

//负责管理倒计时功能
class TimeDownViewModel (application: Application) : AndroidViewModel(application) {
    // LiveData 状态
    private val _remainingTimeMillis = MutableLiveData<Long>(0L)
    val remainingTimeMillis: LiveData<Long> = _remainingTimeMillis

    private val _isRunning = MutableLiveData<Boolean>(false)
    val isRunning: LiveData<Boolean> = _isRunning

    private val _isPaused = MutableLiveData<Boolean>(false)
    val isPaused: LiveData<Boolean> = _isPaused

    private var countDownTimer: CountDownTimer? = null
    private var initialTimeMillis = 0L

    // 启动新计时
    fun startNewTimer(totalMillis: Long) {
        initialTimeMillis = totalMillis
        _remainingTimeMillis.value = totalMillis
        _isRunning.value = true
        _isPaused.value = false
        createCountDownTimer(totalMillis)
    }

    // 暂停计时
    fun pauseTimer() {
        countDownTimer?.cancel()
        _isRunning.value = false
        _isPaused.value = true
    }

    // 继续计时
    fun resumeTimer() {
        _remainingTimeMillis.value?.let { remaining ->
            if (remaining > 0) {
                _isRunning.value = true
                _isPaused.value = false
                createCountDownTimer(remaining)
            }
        }
    }

    // 重置计时
    fun resetTimer() {
        countDownTimer?.cancel()
        _remainingTimeMillis.value = initialTimeMillis
        _isRunning.value = false
        _isPaused.value = false
    }

    // 创建倒计时实例
    private fun createCountDownTimer(totalMillis: Long) {
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(totalMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                _remainingTimeMillis.value = millisUntilFinished
            }

            override fun onFinish() {
                _remainingTimeMillis.value = 0
                _isRunning.value = false
                _isPaused.value = false
            }
        }.start()
    }

    override fun onCleared() {
        countDownTimer?.cancel()
        super.onCleared()
    }
}